﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.ContentManagement;
using Downplay.Gravity.Drivers;
using Downplay.Gravity.Events;
using Downplay.Gravity.Filters;

namespace Downplay.Gravity.Services
{
    public class GravityService : IGravityService
    {
        private IEnumerable<IDataDriver> _dataDrivers;
        private IDictionary<String,List<IDataDriver>> _shapeKeyedDataDrivers;

        public GravityService(IEnumerable<IDataDriver> dataDrivers)
        {
            _dataDrivers = dataDrivers;
            _shapeKeyedDataDrivers = new Dictionary<String,List<IDataDriver>>();

            // Set up dict
            foreach (var d in _dataDrivers) {
                foreach (var s in d.ForShapes()) {
                    if (!_shapeKeyedDataDrivers.ContainsKey(s)) {
                        _shapeKeyedDataDrivers[s] = new List<IDataDriver>();
                    }
                    _shapeKeyedDataDrivers[s].Add(d);
                }
            }
        }

        public bool HandlesShape(string shapeType)
        {
 	        return _shapeKeyedDataDrivers.ContainsKey(shapeType);
        }
                
        public void BuildDecorations(ShapeDataContext context)
        {
            foreach (var d in _shapeKeyedDataDrivers[context.ShapeType]) {
                d.ModifyDataValues(context);
            }
        }

        public AjaxResult HandleAction(Models.GravityData data)
        {
            // TODO: Definitely not so important to optimise here as this only gets run once whenever an action occurs. But still need to take
            // account of which handlers are allowed, authorization, etc.
            var result = new AjaxResult();
            foreach (var d in _dataDrivers)
            {
                d.Action(result, data);
            }
            return result;
        }

        public bool AuthorizeDrop(ShapeDataContext context)
        {
            // TODO: Authorization
            return true;
        }
        
    }
}